<template>
    <van-nav-bar title="发帖" left-text="返回" left-arrow @click-left="onClickLeft" :border="false" class="van-nav-bar">
        <template #right>
            <van-button type="primary" style="height: 2rem;" @click="Sent">发表</van-button>
        </template>
    </van-nav-bar>

    <van-cell-group inset style="background-color:rgb(25, 25, 25)">

        <van-field v-model="title" rows="1" autosize type="textarea" label="标题" placeholder="请输入标题" show-word-limit
            class="van-field" :border="false" />

        <van-field v-model="content" rows="8" autosize type="textarea" placeholder="分享新鲜事..." show-word-limit
            class="van-field" :border="false" />

        <div class="imglist">
            <van-uploader v-model="fileList" multiple preview-size="26.53vw" class="img" :after-read="afterRead"
                :max-count="9" upload-text="上传照片/最多9张" />
        </div>

    </van-cell-group>
</template>

<script setup>
const { proxy } = getCurrentInstance();
const user = proxy.$user.value;

const fileList = ref([]);
const title = ref('');
const content = ref('');
const imglist = ref([]);

if(!user.schoolid){
    proxy.$fail('请先完善个人信息(学校必填)')
}


const afterRead = (files) => {
    // 如果是单文件上传，files是一个对象
    if (!Array.isArray(files)) {
        imglist.value.push(files.file);
    } else {
        // 如果是多文件上传，files是一个数组
        files.forEach(file => {
            imglist.value.push(file.file);
        });
    }
    console.log('提取的文件列表：', imglist.value);
}

//发表
const Sent = async () => {
    const params = {
        title: title.value,
        content: content.value,
        userid: user.id,
        schoolid: user.schoolid,
        imglist: imglist.value,
    }

    const res = await proxy.$http.upload({
        url: '/posts/addpost',
        params: params,
    })

    if (res.code === 1) {
        proxy.$toast(res.msg);

        setTimeout(() => {
            proxy.$router.back();
        }, 1000);
    } else {
        proxy.$toast(res.msg);
    }
}

//返回
const onClickLeft = () => {
    proxy.$router.back();
}
</script>

<style scoped>
.van-nav-bar {
    /* 透明属性 */
    --van-nav-bar-title-text-color: aliceblue;
    background-color: black;
    margin-bottom: 0.5rem;
}

.van-field {
    background-color: transparent;
    color: aliceblue;
    --van-field-input-text-color: aliceblue;
    --van-field-placeholder-text-color: rgba(255, 255, 255, 0.5);
    --van-field-label-width: 2rem;
    --van-field-label-color: aliceblue;
    border: none;
}

.imglist {
    width: 94%;
    margin: 0.5rem auto;
}

.img {
    --van-uploader-border-radius: 0.5rem;
}
</style>
